﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Net;

namespace library
{
    public partial class readerInfo : Form
    {
        public readerInfo()
        {
            InitializeComponent();
        }

        string readerId = ""; //定义全局变量，用于存储客户编号

        private void btn_save_Click(object sender, EventArgs e)
        {
            string username = username_box.Text.Trim(); 
            if(username == "")
            {
                MessageBox.Show("输入用户名");
                return;
            }
            string password = pwd_box.Text.Trim();
            if (lbl_note.Text.Trim() == "添加" && password == "")
            {
                MessageBox.Show("输入用户密码");
                return;
            }
            string name = name_box.Text.Trim();
            if (name == "")
            {
                MessageBox.Show("输入用户姓名");
                return;
            }
            string phone = phone_box.Text.Trim();
            if(phone == "")
            {
                MessageBox.Show("输入用户电话");
                return;
            }
            string expiration_date = expiration_choose.Value.ToString("yyyy-MM-dd");
            
            int sex = rbtn_sex1.Checked ? 1 : 0;
            int readerCate = 0;
            if(readerCate_box.SelectedIndex == readerCate_box.Items.IndexOf("学生"))
            {
                readerCate = 3;
            }else if(readerCate_box.SelectedIndex == readerCate_box.Items.IndexOf("职工"))
            {
                readerCate = 2;
            }else if(readerCate_box.SelectedIndex == readerCate_box.Items.IndexOf("教师"))
            {
                readerCate = 1;
            }
            string remark = remark_box.Text.Trim();
            if(lbl_note.Text == "添加")
            {
                
                string sql = string.Format("INSERT INTO readerinfo (username, password, readerCateId, name, sex, phone, registerDate, expirationDate, borNum, cumBorNum, loss, violateNum, remark) VALUES ('{0}', '{1}', {2}, '{3}', {4}, '{5}', '{6}', '{7}', 0, 0, 0, 0, '{8}')",username,password,readerCate,name,sex,phone, DateTime.Now.ToString("yyyy-MM-dd"), expiration_date, remark);
                MySqlConnection conn = new MySqlConnection("server=localhost; database=librarysystem; UID=root; PWD = 123456; port = 3306");
                conn.Open();
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                int i = cmd.ExecuteNonQuery();
                conn.Close();
                if (i > 0)
                {
                    MessageBox.Show("添加用户成功");
                    ClearTexBox(); //调用函数，清空各控件
                    DataBind_reader();
                }
                else
                {
                    MessageBox.Show("添加用户失败");
                    return;
                }
            }else if(lbl_note.Text.Trim() == "修改")
            {
                MySqlConnection conn = new MySqlConnection("server=localhost; database=librarysystem; UID=root; PWD = 123456; port = 3306");
                conn.Open();
                int loss = loss_box.SelectedIndex;
                string str = string.Format("update readerinfo set username = '{0}', readerCateId = {1}, name = '{2}', sex ={3},phone = '{4}',expirationDate = '{5}',loss = {6},remark='{7}' where readerId = {8};", username, readerCate, name, sex, phone, expiration_date, loss, remark, readerId);
                MySqlCommand cmd = new MySqlCommand(str, conn);
                int i = cmd.ExecuteNonQuery();
                conn.Close();
                if (i > 0)
                {
                    MessageBox.Show("信息修改成功！");
                    DataBind_reader(); //重新加载客户信息
                }
                else
                {
                    MessageBox.Show("信息修改失败！");
                }
                lbl_note.Text = "添加";
                ClearTexBox();
            }
        }
        //清空各控件
        protected void ClearTexBox()
        {
            username_box.Text = "";
            pwd_box.Text = "";
            name_box.Text = "";
            phone_box.Text = "";
            remark_box.Text = "";
            readerId = "";
        }

        //加载客户信息
        protected void DataBind_reader()
        {
            MySqlConnection conn = new MySqlConnection("server=localhost; database=librarysystem; UID=root; PWD = 123456; port = 3306");
            conn.Open();
            string str = "select * from readerinfo";
            MySqlDataAdapter da = new MySqlDataAdapter(str, conn);
            DataTable dt = new DataTable();
            da.Fill(dt);
            conn.Close();
            listView1.Items.Clear();
            foreach (DataRow dr in dt.Rows)
            {
                ListViewItem myitem = new ListViewItem(dr["username"].ToString());
                if(dr["readerCateId"].ToString() == "1")
                {
                    myitem.SubItems.Add("教师");
                }else if(dr["readerCateId"].ToString() == "2")
                {
                    myitem.SubItems.Add("职工");
                }else if(dr["readerCateId"].ToString() == "3")
                {
                    myitem.SubItems.Add("学生");
                }
                myitem.SubItems.Add(dr["name"].ToString()); 
                if(dr["sex"].ToString() == "1")
                {
                    myitem.SubItems.Add("男");
                }else if (dr["sex"].ToString() == "0")
                {
                    myitem.SubItems.Add("女");
                }
                myitem.SubItems.Add(dr["phone"].ToString()); 
                myitem.SubItems.Add(dr["registerDate"].ToString()); 
                myitem.SubItems.Add(dr["expirationDate"].ToString());
                myitem.SubItems.Add(dr["borNum"].ToString());
                myitem.SubItems.Add(dr["cumBorNum"].ToString());
                if(dr["loss"].ToString() == "1")
                {
                    myitem.SubItems.Add("已挂失");
                }else if(dr["loss"].ToString() == "0")
                {
                    myitem.SubItems.Add("未挂失");
                }
                
                myitem.SubItems.Add(dr["violateNum"].ToString());
                myitem.SubItems.Add(dr["remark"].ToString());
                listView1.Items.Add(myitem); //将新建项添加到 ListView 控件中
            }

        }
        private void readerInfo_Load(object sender, EventArgs e)
        {
            DataBind_reader();
            rbtn_sex1.Checked = true;
            int year = System.DateTime.Now.Year;
            int month = System.DateTime.Now.Month;
            int day = System.DateTime.Now.Day;
            expiration_choose.Value = new DateTime(year,month,day);
            readerCate_box.SelectedIndex = readerCate_box.Items.IndexOf("学生");
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0) //如果有选中项
            {
                ListViewItem myitem = listView1.SelectedItems[0]; //获取选中的第一行（一次只能选一行）
                username_box.Text = myitem.SubItems[0].Text; //将选中行第 1 列的值赋值全局变量，客户编号
                readerCate_box.SelectedIndex = readerCate_box.Items.IndexOf(myitem.SubItems[1].Text);
                name_box.Text = myitem.SubItems[2].Text; 
                rbtn_sex1.Checked = myitem.SubItems[3].Text == "男" ? true : false; //性别
                rbtn_sex2.Checked = myitem.SubItems[3].Text == "女" ? true : false; //性别
                phone_box.Text = myitem.SubItems[4].Text;

                int year = Convert.ToInt32(myitem.SubItems[6].Text.Split(' ')[0].Split('/')[0]);
                int month = Convert.ToInt32(myitem.SubItems[6].Text.Split(' ')[0].Split('/')[1]);
                int day = Convert.ToInt32(myitem.SubItems[6].Text.Split(' ')[0].Split('/')[2]);
                expiration_choose.Value = new DateTime(year,month,day);
                remark_box.Text = myitem.SubItems[11].Text;
                loss_box.SelectedIndex = loss_box.Items.IndexOf("是");
                lbl_note.Text = "修改";
                MySqlConnection conn = new MySqlConnection("server=localhost; database=librarysystem; UID=root; PWD = 123456; port = 3306");
                conn.Open();
                string str = string.Format("select readerId from readerinfo where name = '{0}'",name_box.Text.Trim());
                MySqlDataAdapter da = new MySqlDataAdapter(str, conn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {
                    readerId = dr["readerId"].ToString();
                }
            }
        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            ClearTexBox();
        }

        private void delete_btn_Click(object sender, EventArgs e)
        {
            if (readerId == "") //如果没有选中要删除的客户信息
            {
                MessageBox.Show("请先选择要删除的读者信息");
            }
            else
            {
                //弹出删除确认提示框
                DialogResult result = MessageBox.Show("确定要删除选中的读者信息吗？", "删除提示",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes) //如果确定删除
                {
                    MySqlConnection conn = new MySqlConnection("server=localhost; database=librarysystem; UID=root; PWD = 123456; port = 3306");
                    conn.Open();
                    string str = string.Format("delete from readerinfo where readerId ={0}",readerId);
                    MySqlCommand cmd = new MySqlCommand(str, conn);
                    int i = cmd.ExecuteNonQuery();
                    conn.Close();
                    if (i > 0)
                    {
                        MessageBox.Show("删除成功");
                        ClearTexBox();
                        DataBind_reader(); 
                    }
                    else
                    {
                        MessageBox.Show("读者信息删除失败！");
                    }
                }
            }
        }

        private void return_btn_Click(object sender, EventArgs e)
        {
            this.Hide();
            Main frm = new Main();
            frm.Show();
        }
    }
}
